package com.sth.guarded;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Author: sitianhong
 * @Description:
 * @Since: create in 2021/6/12 0012 19:56
 */
public class GuardedQueue {
    private final Queue<Integer> souceList;

    public GuardedQueue() {
        this.souceList = new LinkedBlockingQueue<>();
    }

    public synchronized Integer get() {
        while (souceList.isEmpty()) {
            try {
                System.out.println("等待");
                wait(); // 如果队列为空等待
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return souceList.peek();
    }

    public synchronized void put(Integer e) {
        souceList.add(e);
        System.out.println("唤醒");
        notifyAll();// 通知继续执行
    }
}
